#!/bin/bash

PACKAGE_PATH="$1"
INSTALL_PATH="$2"
INSTALL_VOLUME="$3"
SYSTEM_ROOT="$4"

# The purpose of this postflight script is to make sure the package receipt is
# backed up to the application support directory.

PACKAGE_NAME="TuxeraNTFS_compat.pkg"
APPLICATION_SUPPORT_DIR="/Library/Application Support/Tuxera NTFS"
BACKUP_RECEIPT_PATH="${APPLICATION_SUPPORT_DIR}/Receipt_compat.bom"

# Entry point

# Copy the .bom file to the application support directory.
if [ ! -d "${APPLICATION_SUPPORT_DIR}" ]; then
    mkdir -p "${APPLICATION_SUPPORT_DIR}"
    if [ $? -ne 0 ]; then
	echo "[ERROR] Unable to create application support directory \"${APPLICATION_SUPPORT_DIR}\"."
	exit 1
    fi
fi

chflags nouchg "${APPLICATION_SUPPORT_DIR}"
chmod 0755 "${APPLICATION_SUPPORT_DIR}"

if [ -f "${BACKUP_RECEIPT_PATH}" ]; then
    chflags nouchg "${BACKUP_RECEIPT_PATH}"
    rm -f "${BACKUP_RECEIPT_PATH}"
    if [ $? -ne 0 ]; then
	echo "[ERROR] Unable to remove existing backup receipt \"${BACKUP_RECEIPT_PATH}\"."
	exit 1
    fi
fi

if [ -d "${PACKAGE_PATH}" ]; then
    cp "${PACKAGE_PATH}/Contents/Archive.bom" "${BACKUP_RECEIPT_PATH}"
    if [ ! $? -eq 0 ]; then
	echo "[ERROR] Couldn't copy BOM file ${PACKAGE_PATH}/Contents/Archive.bom to ${BACKUP_RECEIPT_PATH}."
	exit 1
    fi
else
    BOM_TEMPDIR=`mktemp -d "/tmp/tuxera_ntfs_for_mac_installer_XXXXXX"`
    if [ ! $? -eq 0 ]; then
	echo "[ERROR] Couldn't create temporary directory for BOM file extraction."
	exit 1
    fi

    pushd "${BOM_TEMPDIR}" > /dev/null

    xar -x -f "${PACKAGE_PATH}" "${PACKAGE_NAME}/Bom"
    if [ ! $? -eq 0 ]; then
	echo "[ERROR] Couldn't extract BOM file ${PACKAGE_NAME}/Bom to ${BOM_TEMPDIR}."
	rm -rf "${BOM_TEMPDIR}"
	exit 1
    fi

    popd > /dev/null

    mv "${BOM_TEMPDIR}/${PACKAGE_NAME}/Bom" "${BACKUP_RECEIPT_PATH}"
    if [ ! $? -eq 0 ]; then
	echo "[ERROR] Couldn't move extracted file (${BOM_TEMPDIR}/${PACKAGE_NAME}/Bom) to proper location (${BACKUP_RECEIPT_PATH})."
	rm -rf "${BOM_TEMPDIR}"
	exit 1
    fi

    rm -rf "${BOM_TEMPDIR}"
    if [ ! $? -eq 0 ]; then
	echo "[ERROR] Error while deleting temporary directory ${BOM_TEMPDIR}."
	exit 1
    fi
fi

chmod 0444 "${BACKUP_RECEIPT_PATH}"
chflags uchg "${BACKUP_RECEIPT_PATH}"
chmod 0555 "${APPLICATION_SUPPORT_DIR}"

# Execution was successful.
exit 0
